package com.example.statemachine.util;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

/**
 * @author jianwei.wang
 * @version v1.0
 * @date 2019/5/14 16:36
 **/
@Component
@Intercepts(
        {
//                @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
                @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
//                @Signature(type = Executor.class,method = "query",args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
//                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        })
public class MyBatisInterceptor implements Interceptor {

    private static final String type = "update";
    private static final String method = "prepare";


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        String methodName = invocation.getMethod().getName();
        //如果只拦截一个方法签名，此处不需要加判断
        if (method.equalsIgnoreCase(methodName)){
            StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
            MetaObject metaObject = MetaObject
                    .forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY,
                            new DefaultReflectorFactory());
            MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
            String sqlCommandType = mappedStatement.getSqlCommandType().toString();
            if (type.equalsIgnoreCase(sqlCommandType)){
                BoundSql boundSql = statementHandler.getBoundSql();
                String sql = boundSql.getSql().toLowerCase();
                String newSql = sql.replace("version = ?", "version = version+1").replace("where", "where version = ? and");
                Field field = boundSql.getClass().getDeclaredField("sql");
                field.setAccessible(true);
                field.set(boundSql, newSql);
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
        System.out.println(properties.getProperty("name"));
    }

}
